import { defineStore } from "pinia"
import { computed, ref } from "vue"
import {
  createProblemSet as apiCreateProblemSet,
  deleteProblemSet as apiDeleteProblemSet,
  generateInviteCode as apiGenerateInviteCode,
  getProblemSetDetail,
  getProblemSetList as apiGetProblemSetList,
  getProblemSetMembers as apiGetProblemSetMembers,
  joinProblemSet as apiJoinProblemSet,
  updateProblemSet as apiUpdateProblemSet
} from "@/api/modules/problem-set"

export const useProblemSetsStore = defineStore("problemSet", () => {
  const problemSets = ref([])
  const loading = ref(false)
  const total = ref(0)
  const currentProblemSet = ref(null)
  const members = ref([])
  const membersTotal = ref(0)

  const myProblemSets = computed(() => {
    return problemSets.value.filter(set => set.userRole)
  })

  const publicProblemSets = computed(() => {
    return problemSets.value.filter(set => set.isPublic)
  })

  async function getProblemSetList(params = {}) {
    loading.value = true
    try {
      const response = await apiGetProblemSetList(params)

      if (response && response.code === 200 && response.data) {
        const data = response.data
        problemSets.value = Array.isArray(data.records) ? data.records : []
        total.value = data.total === 0 && problemSets.value.length > 0 ? problemSets.value.length : typeof data.total === "number" ? data.total : 0
        return response
      } else {
        problemSets.value = []
        total.value = 0
        throw new Error(response?.message || "获取题目集列表失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function getProblemSetById(id) {
    loading.value = true
    try {
      const response = await getProblemSetDetail(id)

      if (response && response.code === 200 && response.data) {
        currentProblemSet.value = response.data
        return response
      } else {
        throw new Error(response?.message || "获取题目集详情失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function createProblemSet(problemSetData) {
    loading.value = true
    try {
      const formattedData = {
        name: problemSetData.name,
        description: problemSetData.description,
        isPublic: problemSetData.isPublic !== undefined ? problemSetData.isPublic : true,
        problemIds: problemSetData.problemIds || []
      }

      const response = await apiCreateProblemSet(formattedData)

      if (response && response.code === 200) {
        return response
      } else {
        throw new Error(response?.message || "创建题目集失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function updateProblemSet(id, problemSetData) {
    loading.value = true
    try {
      const result = await apiUpdateProblemSet(id, problemSetData)

      if (result && (result.code === 200 || result.success === true || result.status === "success" || result.id)) {
        const index = problemSets.value.findIndex(set => set.id === id)
        if (index !== -1) {
          problemSets.value[index] = { ...problemSets.value[index], ...result.data }
        }
        if (currentProblemSet.value?.id === id) {
          currentProblemSet.value = result.data
        }
        return { code: 200, data: result.data || result, message: result.message || "更新成功" }
      } else {
        throw new Error(result?.message || "更新题目集失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function deleteProblemSet(id) {
    loading.value = true
    try {
      const result = await apiDeleteProblemSet(id)

      if (result && (result.code === 200 || result.success === true || result.status === "success")) {
        problemSets.value = problemSets.value.filter(set => set.id !== id)
        total.value = Math.max(0, total.value - 1)
        return { code: 200, message: "删除成功" }
      } else {
        throw new Error(result?.message || "删除题目集失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function joinProblemSet(inviteCode) {
    loading.value = true
    try {
      const result = await apiJoinProblemSet({ inviteCode })

      if (result && (result.code === 200 || result.success === true || result.status === "success")) {
        return { code: 200, message: "加入成功" }
      } else {
        throw new Error(result?.message || "加入题目集失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function generateInviteCode(id, days = 0) {
    loading.value = true
    try {
      const result = await apiGenerateInviteCode(id, days)

      if (result && (result.code === 200 || result.success === true || result.status === "success")) {
        const inviteCodeData = result.data

        if (currentProblemSet.value?.id === id) {
          currentProblemSet.value.inviteCode = inviteCodeData.inviteCode
          currentProblemSet.value.inviteCodeExpiresAt = inviteCodeData.expiresAt
        }
        return { code: 200, data: inviteCodeData, message: "生成成功", isPermanent: inviteCodeData.isPermanent, days }
      } else {
        throw new Error(result?.message || "生成邀请码失败")
      }
    } finally {
      loading.value = false
    }
  }

  async function getMembers(id, params = {}) {
    loading.value = true
    try {
      const result = await apiGetProblemSetMembers(id, params)

      if (result && result.code === 200) {
        const data = result.data || {}
        members.value = Array.isArray(data.records) ? data.records : []
        membersTotal.value = typeof data.total === "number" ? data.total : 0
        return result
      } else {
        members.value = []
        membersTotal.value = 0
        throw new Error(result?.message || "获取成员列表失败")
      }
    } finally {
      loading.value = false
    }
  }

  function resetStore() {
    problemSets.value = []
    total.value = 0
    currentProblemSet.value = null
    members.value = []
    membersTotal.value = 0
    loading.value = false
  }

  return {
    problemSets,
    loading,
    total,
    currentProblemSet,
    members,
    membersTotal,
    myProblemSets,
    publicProblemSets,
    getProblemSetList,
    getProblemSetById,
    createProblemSet,
    updateProblemSet,
    deleteProblemSet,
    joinProblemSet,
    generateInviteCode,
    getMembers,
    resetStore
  }
})
